import redis


class RedisUtil:

    def __init__(self, db=0):
        self.rds = redis.StrictRedis(db=db, decode_responses=True)

    def set_str(self, redis_key, value, expire_second=0):
        '''
        设置redis字符串
        :param redis_key:
        :param value:
        :param expire_second:
        :return:
        '''
        if expire_second:
            self.rds.set(redis_key, value, ex=expire_second)
        else:
            self.rds.set(redis_key, value)

    def get_str(self, redis_key):
        '''
        获取redis字符串
        :param redis_key:
        :return:
        '''
        return self.rds.get(redis_key)

    def set_list(self, redis_key, one_list, expire_second=0):
        '''
        设置一个新集合，如果这个集合已经存在，则执行添加操作
        :param redis_key:
        :param one_list:
        :param expire_second:
        :return:
        '''
        pipe = self.rds.pipeline()
        for one in one_list:
            pipe.rpush(redis_key, one)
        if expire_second:
            pipe.expire(redis_key, expire_second)
        pipe.execute()

    def get_list(self, redis_key):
        '''
        获取一个集合
        :param redis_key:
        :return:
        '''
        redis_key_len = self.rds.llen(redis_key)
        if redis_key_len:
            return self.rds.lrange(redis_key, 0, redis_key_len)
        else:
            return []
